package com.czp.infosharingplatformapp.service.impl;

import com.czp.infosharingplatformapp.dto.CategoryResponse;
import com.czp.infosharingplatformapp.model.Category;
import com.czp.infosharingplatformapp.model.Post;
import com.czp.infosharingplatformapp.repository.CategoryRepository;
import com.czp.infosharingplatformapp.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    public List<Category> getAllCategories() {
        return categoryRepository.findAll(); // 使用 JPA 提供的 findAll 方法
    }

    @Override
    public List<Category> findAllTopCategories() {
        return categoryRepository.findByParentIsNull();
    }

    @Override
    public List<Category> findSubCategories(Long parentId) {
        Category parent = categoryRepository.findById(parentId).orElse(null);
        return categoryRepository.findByParent(parent);
    }

    @Override
    public Category createCategory(String name, Long parentId) {
        Category category = new Category();
        category.setName(name);
        if (parentId != null) {
            Category parent = categoryRepository.findById(parentId).orElse(null);
            category.setParent(parent);
        }
        return categoryRepository.save(category);
    }

    @Override
    public void deleteCategory(Long categoryId) {
        categoryRepository.deleteById(categoryId);
    }

    // 获取所有子分类
    @Override
    public List<Category> getAllSubCategories() {
        List<Category> topCategories = findAllTopCategories();
        List<Category> allSubCategories = new ArrayList<>();
        for (Category topCategory : topCategories) {
            getAllSubCategoriesRecursively(topCategory, allSubCategories);
        }
        return allSubCategories;
    }

    private void getAllSubCategoriesRecursively(Category parentCategory, List<Category> allSubCategories) {
        List<Category> subCategories = findSubCategories(parentCategory.getId());
        allSubCategories.addAll(subCategories);
        for (Category subCategory : subCategories) {
            getAllSubCategoriesRecursively(subCategory, allSubCategories);
        }
    }

    public CategoryResponse convertToCategoryResponse(Category category) {
        CategoryResponse response = new CategoryResponse();
        response.setId(category.getId());
        response.setName(category.getName());
        if (category.getParent() != null) {
            response.setParentId(category.getParent().getId());
        }
        response.setCreatedAt(category.getCreatedAt());
        response.setUpdatedAt(category.getUpdatedAt());
        response.setPostIds(category.getPosts().stream().map(Post::getId).collect(Collectors.toList()));
        return response;
    }

    @Override
    public void initializeCategories() {
        // 检查数据库中是否有固定分类，如果没有则初始化写死的分类
        if (categoryRepository.count() == 0) {  // 只有当没有数据时才插入
            // 一级分类
            Category math = new Category();
            math.setName("数学");
            categoryRepository.save(math);

            Category english = new Category();
            english.setName("英语");
            categoryRepository.save(english);

            Category major = new Category();
            major.setName("专业");
            categoryRepository.save(major);

            // 二级分类 - 数学下的分类
            Category math1 = new Category();
            math1.setName("数学一");
            math1.setParent(math);
            categoryRepository.save(math1);

            Category math2 = new Category();
            math2.setName("数学二");
            math2.setParent(math);
            categoryRepository.save(math2);

            // 二级分类 - 英语下的分类
            Category english1 = new Category();
            english1.setName("英语一");
            english1.setParent(english);
            categoryRepository.save(english1);

            Category english2 = new Category();
            english2.setName("英语二");
            english2.setParent(english);
            categoryRepository.save(english2);

            // 二级分类 - 专业下的分类
            Category cs408 = new Category();
            cs408.setName("计算机学科专业基础（408）");
            cs408.setParent(major);
            categoryRepository.save(cs408);

            System.out.println("初始化分类完成！");
        }
    }
}